﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MiniFox.Platform;
using MiniFox.Security;
using MiniFox.Web.Infrastructure;
using System.Net;
using System.Text;
using Wechat.Core;

namespace Wechat.Corp.Api
{
    /// <summary>
    /// 
    /// </summary>
    [NoCache]
    public class CorpController : WechatControllerBase<IWechatAgentService>
    {
        #region 微信验证
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="msg_signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public override HttpResponseMessage Validate([FromRoute(Name = GlobalKey.NAME)]string name, string msg_signature, string timestamp, string nonce, string echostr)
        {
            var service = this.CreateService(name);
            string token = service.Token;

            string[] arr = { token, timestamp, nonce, echostr };
            Array.Sort(arr);
            string temp = string.Join(string.Empty, arr).SHA1EncryptToHexString();
            if (string.Equals(msg_signature, temp, StringComparison.OrdinalIgnoreCase))
            {
                const int len = 16;
                byte[] key = Convert.FromBase64String(service.AesKey);
                byte[] iv = new byte[len];
                Array.Copy(key, iv, len);

                var rijndael = new RijndaelCryptoService(key, iv);

                byte[] originalBytes = rijndael.Decrypt(Convert.FromBase64String(echostr));
                int byteLength = BitConverter.ToInt32(originalBytes, len);
                byteLength = IPAddress.NetworkToHostOrder(byteLength);

                byte[] msgBytes = new byte[byteLength];
                byte[] corpIdBytes = new byte[originalBytes.Length - 20 - byteLength];
                Array.Copy(originalBytes, 20, msgBytes, 0, byteLength);
                Array.Copy(originalBytes, 20 + byteLength, corpIdBytes, 0, originalBytes.Length - 20 - byteLength);
                string msgStr = Encoding.UTF8.GetString(msgBytes);
                string corpId = Encoding.UTF8.GetString(corpIdBytes);

                HttpResponseMessage response = new HttpResponseMessage();
                response.Content = new StringContent(msgStr);
                return response;
            }
            else
            {
                throw new MiniFox.Exceptions.SystemException("signature:" + temp);
            }
        }
        #endregion
    }
}
